# -*- coding: utf-8 -*-
# @FileName : Wallet.py
# @Time     : 2023/6/10 11:04
# @Author   : Zhong Runke
from flask import request, g, jsonify
from application import app, db
from web.controller.api import route_api
from common.models.WalletInfo import WalletInfo
from common.models.Wallet import Wallet
from common.libs.Helper import getCurrentDate
import json
from common.libs.webase.WebaseService import WebaseService

@route_api.route("/wallet/recharge", methods=["POST"])
def walletRecharge():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    req = request.values
    print(req)
    user_id = int(req['user_id']) if 'user_id' in req else 0
    userAddress = req['userAddress'] if 'userAddress' in req else ''
    money = float(req['money']) if 'money' in req else 0

    if user_id <= 0 or user_id is None:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)

    if len(userAddress) < 5 or userAddress is None:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)

    if money <= 0 or money is None:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)

    # 根据第三方流水号查询

    # 创建钱包充值信息
    model_walletinfo = WalletInfo()
    model_walletinfo.userAddress = userAddress
    model_walletinfo.created_time = model_walletinfo.updated_time = getCurrentDate()
    model_walletinfo.type = 0 # 0充值 1提现
    model_walletinfo.status = 0
    model_walletinfo.price = money

    # 调用微信支付

    amount = int(model_walletinfo.price * 100)
    # 调用区块链充值
    webase_resp = WebaseService.commonReq(userAddress, "rechargeWallet",
                                          [amount],
                                          app.config['WEBASE_CONTRACTABI'],
                                          app.config['WEBASE_CONTRACTNAME'],
                                          app.config['WEBASE_CONTRACTADDRESS'])
    webase_dict = json.loads(webase_resp)
    if webase_dict['message'] == 'Success':
        # 修改数据库里的钱
        print(webase_dict)
        try:
            wallet = Wallet.query.filter_by(useraddress=userAddress).first()
            wallet.balance = float(wallet.balance) + money
            wallet.updated_time = getCurrentDate()
            db.session.add(wallet)

            model_walletinfo.updated_time = getCurrentDate()
            model_walletinfo.blocknum = webase_dict['blockNumber']
            model_walletinfo.transactionhash = webase_dict['transactionHash']
            model_walletinfo.blockHash = webase_dict['blockHash']
            db.session.add(model_walletinfo)
            db.session.commit()
        except:
            resp['code'] = -1
            resp['msg'] = '数据库异常'
            return jsonify(resp)
    else:
        resp['code'] = -1
        resp['msg'] = '区块链异常'
        return jsonify(resp)

    resp['data']['pay_info'] = {
        'timeStamp': model_walletinfo.created_time,
        'nonceStr': 'none',
        'package': 'none',
        'signType': 'MD5',
        'paySign': 'sign'
    }
    return jsonify(resp)


@route_api.route("/wallet/withdrawal", methods=["POST"])
def walletWithdrawal():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    req = request.values
    print(req)
    user_id = int(req['user_id']) if 'user_id' in req else 0
    userAddress = req['userAddress'] if 'userAddress' in req else ''
    money = float(req['money']) if 'money' in req else 0

    wallet = Wallet.query.filter_by(useraddress=userAddress).first()
    if wallet.balance < money:
        resp['code'] = -1
        resp['msg'] = '提现代币超出了余额'
        return jsonify(resp)

    if user_id <= 0 or user_id is None:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)

    if len(userAddress) < 5 or userAddress is None:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)

    if money <= 0 or money is None:
        resp['code'] = -1
        resp['msg'] = '参数错误'
        return jsonify(resp)

    # 根据第三方流水号查询

    # 创建钱包充值信息
    model_walletinfo = WalletInfo()
    model_walletinfo.userAddress = userAddress
    model_walletinfo.created_time = model_walletinfo.updated_time = getCurrentDate()
    model_walletinfo.type = 1 # 0充值 1提现
    model_walletinfo.status = 0
    model_walletinfo.price = money

    # 调用微信支付
    # 调用微信支付后修改状态 status

    amount = int(model_walletinfo.price * 100)
    # 调用区块链充值
    webase_resp = WebaseService.commonReq(userAddress, "withdrawWallet",
                                          [amount],
                                          app.config['WEBASE_CONTRACTABI'],
                                          app.config['WEBASE_CONTRACTNAME'],
                                          app.config['WEBASE_CONTRACTADDRESS'])
    webase_dict = json.loads(webase_resp)
    if webase_dict:
        # 修改数据库里的钱
        print(webase_dict)
        try:
            wallet.balance = float(wallet.balance) - money
            wallet.updated_time = getCurrentDate()
            db.session.add(wallet)
            db.session.commit()

            model_walletinfo.updated_time = getCurrentDate()
            model_walletinfo.blocknum = webase_dict['blockNumber']
            model_walletinfo.transactionhash = webase_dict['transactionHash']
            model_walletinfo.blockHash = webase_dict['blockHash']
            db.session.add(model_walletinfo)
            db.session.commit()
        except:
            resp['code'] = -1
            resp['msg'] = '数据库异常'
            return jsonify(resp)
    else:
        resp['code'] = -1
        resp['msg'] = '区块链异常'
        return jsonify(resp)

    resp['data']['pay_info'] = {
        'timeStamp': model_walletinfo.created_time,
        'nonceStr': 'none',
        'package': 'none',
        'signType': 'MD5',
        'paySign': 'sign'
    }
    return jsonify(resp)
